package com.example.blog.admin.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.blog.dao.mapper.ArticleMapper;
import com.example.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ThreadService {


    @Async("taskExecutor")
    public void updateViewCount(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article articleUpdateViewCount = new Article();
        articleUpdateViewCount.setViewCounts(viewCounts + 1);
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId, article.getId());
        // 设置一个  为了在多线程的环境下 线程安全
        updateWrapper.eq(Article::getViewCounts, viewCounts);
        // update article set view_count = 100 where id = 1 and viewCounts = oldViewCounts
        articleMapper.update(articleUpdateViewCount, updateWrapper);

        try {
            // 睡眠5秒钟，不会对主线程造成影响
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新操作完成了");
    }
}
